import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';

class CacheManager {
  // 生成缓存键
  static String generateCacheKey(String path, Map<String, dynamic>? queryParameters) {
    var key = path;
    if (queryParameters != null) {
      key += '?' + Uri(queryParameters: queryParameters).query;
    }
    return key;
  }

  // 缓存响应数据
  static Future<void> cacheResponse(String cacheKey, dynamic responseData) async {
    try {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      String jsonData = jsonEncode(responseData);
      prefs.setString(cacheKey, jsonData);
    } catch (e) {
      print('缓存数据出错: $e');
    }
  }

  // 获取缓存响应数据
  static Future<dynamic> getCachedResponse(String cacheKey) async {
    try {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      String? jsonData = prefs.getString(cacheKey);
      if (jsonData != null) {
        return jsonDecode(jsonData);
      }
    } catch (e) {
      print('读取缓存数据出错: $e');
    }
    return null;
  }
}    